import React, { useState, useRef, useEffect } from 'react';
import style from './index.less'; // 确保你有一个样式文件来定义样式

const MarqueeMenuItem = ({ children, styles }) => {
  const containerRef = useRef(null);
  const textRef = useRef(null);
  const [isOverflowing, setIsOverflowing] = useState(false);
  const [scrollPosition, setScrollPosition] = useState(0);
  const animationRef = useRef(null);
  const timeoutRef = useRef(null);
  const timeoutRef1 = useRef(null);

  // 检测文字是否超出容器宽度
  useEffect(() => {
    const checkOverflow = () => {
      if (containerRef.current && textRef.current) {
        let menuItemRenderTimeout = setTimeout(() => {
          const containerWidth = containerRef?.current?.offsetWidth || 102;
          const textWidth = textRef?.current?.scrollWidth;
          setIsOverflowing(textWidth > containerWidth);
          clearTimeout(menuItemRenderTimeout);
        });
      }
    };

    // 初始检测
    checkOverflow();

    // 添加resize监听
    window.addEventListener('resize', checkOverflow);

    return () => {
      window.removeEventListener('resize', checkOverflow);
      if (animationRef.current) {
        cancelAnimationFrame(animationRef.current);
      }
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
      if (timeoutRef1.current) {
        clearTimeout(timeoutRef1.current);
      }
    };
  }, [children]);

  // 开始滚动动画
  const startAnimation = () => {
    if (!isOverflowing) return;

    const containerWidth = containerRef?.current?.offsetWidth;
    const textWidth = textRef?.current?.scrollWidth;
    const distance = textWidth - containerWidth + 8;

    let startTime = null;
    const speed = 0.04; // 滚动速度（像素/毫秒）

    const animate = (timestamp) => {
      if (!startTime) startTime = timestamp;
      const progress = timestamp - startTime;
      const scroll = Math.min(distance, progress * speed);

      setScrollPosition(scroll);

      if (scroll < distance) {
        animationRef.current = requestAnimationFrame(animate);
      } else {
        // 滚动完成后等待1.5秒重置
        timeoutRef.current = setTimeout(() => {
          setScrollPosition(0);
          startTime = null;
          timeoutRef1.current = setTimeout(() => {
            animationRef.current = requestAnimationFrame(animate);
          }, 1000);
        }, 1500);
      }
    };

    animationRef.current = requestAnimationFrame(animate);
  };

  // 停止动画
  const stopAnimation = () => {
    if (animationRef.current) {
      cancelAnimationFrame(animationRef.current);
      animationRef.current = null;
    }
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
      timeoutRef.current = null;
    }
    if (timeoutRef1.current) {
      clearTimeout(timeoutRef1.current);
      timeoutRef.current = null;
    }
    setScrollPosition(0);
  };

  const handleMouseEnter = () => {
    startAnimation();
  };

  const handleMouseLeave = () => {
    stopAnimation();
  };

  return (
    <div
      className={style.marqueeContainer}
      style={styles}
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
    >
      <div
        className={style.marqueeContentContainer}
        ref={containerRef}
        style={{
          position: 'relative',
          overflow: 'hidden',
          height: '100%',
          width: '100%',
        }}
      >
        <div
          ref={textRef}
          className={style.marqueeText}
          style={{
            whiteSpace: 'nowrap',
            position: 'absolute',
            left: 0,
            top: '50%',
            transform: `translateX(-${scrollPosition}px) translateY(-50%)`,
            transition: 'transform 0.15s ease',
          }}
        >
          {children}
        </div>
      </div>
    </div>
  );
};

// 可选的默认样式

export default MarqueeMenuItem;
